package com.coderli.shurnim.common;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

/**
 * 通用的<em>Hibernate</em>基类，封装对数据库基本的<b>CRUD</b>操作
 * 
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
public class GenericHibernateDAO<T> {

	private Class<T> persistentClass;
	private SessionFactory sessionFactory;

	protected GenericHibernateDAO(Class<T> persistentClass,
			SessionFactory sessionFactory) {
		this.persistentClass = persistentClass;
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 获取当前Session引用
	 * 
	 * @return
	 * @author lihzh
	 * @alia OneCoder
	 */
	protected Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}

	/**
	 * 获取所有对象
	 * 
	 * @return
	 * @author lihzh
	 * @alia OneCoder
	 */
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return getSession().createCriteria(persistentClass).list();
	}

	/**
	 * 根据属性名获取唯一的实体对象
	 * 
	 * @param propName
	 *            属性名
	 * @param propValue
	 *            属性值
	 * @return
	 * @author lihzh
	 * @date 2012-10-23 下午3:08:43
	 */
	@SuppressWarnings("unchecked")
	protected T findUniqueEntityByProp(String propName, String propValue) {
		return (T) getSession().createCriteria(persistentClass)
				.add(Restrictions.eq(propName, propValue)).list().get(0);
	}
}
